<template>
  <div class="roles">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" @click="addRoleBtn" size="medium">添加角色</el-button>
      <el-table stripe :data="rolesData" border style="width: 100%">
        <el-table-column type="expand" width="50" class="expand">
          <template v-slot="scope">
            <el-row
              class="firwrapper bdbottom"
              :class="index1 === 0 ? 'bdtop':''"
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="4">
                <el-tag class="tagfirst" :type="''">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">
                <el-row
                  class="firwrapper"
                  :class="index2 == item1.children.length-1 ? '':'bdbottom'"
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="5">
                    <el-tag class="tagfirst" :type="'success'">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="13">
                    <el-tag
                      class="insertTag"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      :type="'warning'"
                      @close="delTag(item3.id,scope.row)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="edit" label="操作">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoleBtn(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delRole(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              @click="setRolesBtn(scope.row)"
              icon="el-icon-setting"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的弹窗 -->
    <el-dialog
      :title="updateRole"
      width="50%"
      @closed="closeAddRoleDialog"
      :visible.sync="dialogRoleVisible"
    >
      <el-form
        :model="rolesForm"
        :rules="rolesRules"
        ref="rolesForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-focus v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRole">确 定</el-button>
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的弹窗 -->
    <el-dialog
      title="分配权限"
      @closed="clearRightsTree"
      :visible.sync="dialogSetRoleVisible"
      width="50%"
    >
      <el-tree
        :data="rightsData"
        :default-checked-keys="checkKeys"
        :props="rightsProps"
        @check-change="getCheckedKeys"
        node-key="id"
        default-expand-all
        :show-checkbox="true"
        ref="tree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSetRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesData: [],
      // 保存权限列表
      rightsData: [],
      updateRole: '',
      // 控制添加角色弹窗
      dialogRoleVisible: false,
      // 控制分配权限弹窗
      dialogSetRoleVisible: false,

      rolesForm: {
        roleName: '', // 角色名称
        roleDesc: '' // 角色描述
      },
      // 配置权限对应属性
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      // 保存默认选中的父节点
      checkKeys: [],
      rolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请描述下该角色', trigger: 'blur' }
        ]
      },
      editRoleId: '',
      // 被授权角色id
      setRightRoleId: '',
      // 被授权的id列表字符串
      getRightsStr: ''
    }
  },
  created() {
    // 获取角色列表
    this.getRoles()
  },
  mounted() {},
  methods: {
    async getRoles() {
      const { data: res } = await this.$axios.get('roles')
      this.rolesData = res.data
    },

    // 添加角色按钮
    addRoleBtn() {
      this.rolesForm.roleName = ''
      this.rolesForm.roleDesc = ''
      this.updateRole = '添加角色'
      this.dialogRoleVisible = true
    },
    // 添加角色
    addRole() {
      this.$refs.rolesForm.validate(async valid => {
        if (!valid) return this.$message.error('添加角色失败')
        if (this.updateRole === '添加角色') {
          const { data: res } = await this.$axios.post('roles', this.rolesForm)
          if (res.meta.status !== 201)
            return this.$message.error('添加角色失败')
          this.getRoles()

          this.$message.success('添加角色成功')
          console.log('添加。。。。')
        } else {
          const { data: res } = await this.$axios.put(
            'roles/' + this.editRoleId,
            {
              roleName: this.rolesForm.roleName,
              roleDesc: this.rolesForm.roleDesc
            }
          )
          if (res.meta.status !== 200)
            return this.$message.error('角色修改失败')
          this.getRoles()
          this.$message.success('修改角色成功')
          console.log('编辑。。。。')
          console.log(res)
        }
        this.dialogRoleVisible = false
      })
    },
    delRole(id) {
      // 删除角色
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$axios.delete('roles/' + id)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.$message.success('删除成功')
          this.getRoles()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 添加角色弹窗关闭后的事件
    closeAddRoleDialog() {
      this.$refs.rolesForm.resetFields()
    },
    // 编辑角色
    editRoleBtn(roleInfo) {
      this.updateRole = '编辑角色'
      this.editRoleId = roleInfo.id
      this.rolesForm.roleName = roleInfo.roleName
      this.rolesForm.roleDesc = roleInfo.roleDesc
      this.dialogRoleVisible = true
    },
    // 删除用户角色
    async delTag(rigthId, role) {
      const { data: res } = await this.$axios.delete(
        `roles/${role.id}/rights/${rigthId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      role.children = res.data
      this.$message.success('取消权限成功')
    },
    // 分配权限弹窗
    async setRolesBtn(role) {
      this.setRightRoleId = role.id
      const { data: res } = await this.$axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      this.rightsData = res.data
      this.getRightsKeys(role, this.checkKeys)
      this.dialogSetRoleVisible = true
    },
    // 授权操作
    async setRights() {
      const { data: res } = await this.$axios.post(
        `roles/${this.setRightRoleId}/rights`,
        {
          rids: this.getRightsStr
        }
      )
      if (res.meta.status !== 200) return this.$message.error('授权失败')
      this.$message.success('您当前成功授权')
      this.getRoles()
      this.dialogSetRoleVisible = false
    },
    // 用递归获取当前角色拥有的所有权限id，病保存到checkKeys中
    getRightsKeys(node, arr) {
      // 如果当前node节点不包含children树形，
      // 则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getRightsKeys(item, arr)
      })
    },
    // 获取选中节点
    getCheckedKeys() {
      this.getRightsStr = this.$refs.tree.getCheckedKeys().join(',')
      let str = this.$refs.tree.getHalfCheckedKeys().join(',')
      this.getRightsStr = str + ',' + this.getRightsStr
      // console.log(this.getRightsStr)
    },
    // 弹窗关闭时
    clearRightsTree() {
      this.checkKeys = []
    }
  },
  directives: {
    focus: {
      // 指令的定义
      inserted: function(el) {
        el.focus()
      }
    }
  }
}
</script>

<style lang='less' scoped>
.firwrapper {
  display: flex;
  align-items: center;
  justify-content: start;
}
.tagfirst {
  width: 88px;
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #f2f2f2;
}
.bdbottom {
  border-bottom: 1px solid #f2f2f2;
}
.insertTag {
  margin: 10px;
}
.expand {
  transition: all 0.5s;
}
</style>
